package com.xmut.mall.coupon.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrBuilder;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.mall.coupon.dao.FullDiscountDao;
import com.xmut.mall.coupon.entity.FullDiscountEntity;
import com.xmut.mall.coupon.entity.PromotionGoodsEntity;
import com.xmut.mall.coupon.feign.ProductFeignService;
import com.xmut.mall.coupon.searchparams.ManagerFullDiscountSearchParam;
import com.xmut.mall.coupon.searchparams.SellerFullDiscountSearchParam;
import com.xmut.mall.coupon.service.FullDiscountService;
import com.xmut.mall.coupon.service.PromotionGoodsService;
import com.xmut.mall.coupon.utils.PageUtil;
import com.xmut.mall.coupon.utils.RespBean;
import com.xmut.mall.coupon.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service("fullDiscountService")
public class FullDiscountServiceImpl extends ServiceImpl<FullDiscountDao, FullDiscountEntity> implements FullDiscountService {

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private PromotionGoodsService promotionGoodsService;

    /**
     * 添加满减
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean addFullDiscount(AddFullDiscountVo vo) {
        FullDiscountEntity entity = new FullDiscountEntity();
        Long id = IdWorker.getId();
        entity.setId(id);
        entity.setCreateTime(new Date());
        entity.setPromotionName(vo.getPromotionName());
        entity.setDescription(vo.getDescription());
        entity.setStartTime(vo.getStartTime());
        entity.setEndTime(vo.getEndTime());
        entity.setFullMoney(vo.getFullMoney());
        entity.setFullMinusFlag(vo.getFullMinusFlag());
        entity.setFreeFreightFlag(vo.getFreeFreightFlag());
        entity.setStoreId(vo.getStoreId());
        entity.setStoreName(vo.getStoreName());
        entity.setFullRateFlag(vo.getFullRateFlag());

        // 满减是满减具体金额类型
        if (vo.getFullMinusFlag()){
            // 减现金
            entity.setFullMinus(vo.getFullMinus());
            // 设置标题
            String title = "满"+vo.getFullMoney()+" 减"+vo.getFullMinus();
            entity.setTitle(title);
        }

        // 满减是折扣类型
        if (vo.getFullRateFlag()){
            // 打折
            entity.setFullRate(vo.getFullRate());
            String title = "满"+vo.getFullMoney()+" 打"+vo.getFullRate()+"折";
            entity.setTitle(title);
        }

        // 满减有送优惠券
        if (vo.getCouponFlag()){
            entity.setCouponFlag(vo.getCouponFlag());
            entity.setCouponId(vo.getCouponId());
        }

        // 满减有送赠品
        if (vo.getGiftFlag()){
            entity.setGiftFlag(vo.getGiftFlag());
            entity.setGiftId(vo.getGiftId());
        }

        // 满减有送积分
        if(vo.getPointFlag()){
            entity.setPointFlag(vo.getPointFlag());
            entity.setPoint(vo.getPoint());
        }

        // 满减活动的使用范围 ALL(全部) PORTION_GOODS(指定了使用范围)
        if (vo.getScopeType().equals("PORTION_GOODS")){
            // 限定了范围的情况
            entity.setScopeType(vo.getScopeType());
            List<PromotionGoodsEntity> promotionGoodsList = vo.getPromotionGoodsList().stream().map(item -> {
                PromotionGoodsEntity promotionGoodsEntity = new PromotionGoodsEntity();
                promotionGoodsEntity.setSkuId(item.getSkuId());
                promotionGoodsEntity.setGoodsName(item.getGoodsName());
                promotionGoodsEntity.setPrice(item.getPrice());
                promotionGoodsEntity.setThumbnail(item.getSkuDefaultImg());
                promotionGoodsEntity.setStoreId(item.getStoreId());
                promotionGoodsEntity.setStoreName(item.getStoreName());
                promotionGoodsEntity.setStartTime(item.getStartTime());
                promotionGoodsEntity.setEndTime(item.getEndTime());
                promotionGoodsEntity.setPromotionId(id);
                promotionGoodsEntity.setScopeType(vo.getScopeType());
                promotionGoodsEntity.setGoodsType("PHYSICAL_GOODS");
                // 活动的类型
                promotionGoodsEntity.setPromotionType("FULL_DISCOUNT");
                promotionGoodsEntity.setCreateTime(new Date());
                return promotionGoodsEntity;
            }).collect(Collectors.toList());
            // 向活动商品表保存当前指定范围的商品
            promotionGoodsService.saveBatch(promotionGoodsList);
        }else {
            // 无限定使用范围 全部商品可用
            entity.setScopeType(vo.getScopeType());
        }

        entity.setCreateTime(new Date());
        boolean save = this.save(entity);

        if (save){
            return RespBean.success("保存成功");
        }else {
            return RespBean.error("保存失败");
        }
    }

    /**
     * 获取卖家端的满减分页数据
     * @param vo
     * @param param
     * @return
     */
    @Override
    public RespBean getSellerFullDiscountPage(PageVO vo, SellerFullDiscountSearchParam param) {
        IPage<SellerFullDiscountPageVo> page = this.baseMapper.getSellerFullDiscountPage(PageUtil.initPage(vo),param,new Date());

        FullDiscountEntity entity = new FullDiscountEntity();

        for (SellerFullDiscountPageVo record : page.getRecords()) {
            BeanUtils.copyProperties(record,entity);
            record.setPromotionStatus(entity.getPromotionStatus());
        }

        return RespBean.success("获取成功",page);
    }

    /**
     * 根据传入的ID获取满减活动的详情
     * @param id
     * @return
     */
    @Override
    public RespBean getFullDiscountDetail(Long id) {
        FullDiscountEntity fullDiscountEntity = this.getById(id);
        AddFullDiscountVo vo = new AddFullDiscountVo();
        BeanUtils.copyProperties(fullDiscountEntity,vo);
        // 如果该优惠券指定了了使用范围就把指定的商品查出来
        if (fullDiscountEntity.getScopeType().equals("PORTION_GOODS")){
            List<PromotionGoodsEntity> promotionGoodsEntityList = promotionGoodsService.list(new QueryWrapper<PromotionGoodsEntity>()
                    .eq("promotion_id", fullDiscountEntity.getId()));
            List<PromotionGoodsVo> promotionGoodsVos = promotionGoodsEntityList.stream().map(item -> {
                PromotionGoodsVo promotionGoods = new PromotionGoodsVo();
                BeanUtils.copyProperties(item,promotionGoods);
                promotionGoods.setSkuDefaultImg(item.getThumbnail());
                return promotionGoods;
            }).collect(Collectors.toList());
            vo.setPromotionGoodsList(promotionGoodsVos);
        }

        return RespBean.success("获取成功",vo);
    }

    /**
     * 修改满减活动
     * @param vo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean editFullDiscount(AddFullDiscountVo vo) {
        FullDiscountEntity entity = new FullDiscountEntity();
        BeanUtils.copyProperties(vo,entity);
        // 修改
        boolean b = this.updateById(entity);

        if (vo.getScopeType().equals("PORTION_GOODS")){
            // 修改关联的商品
            List<PromotionGoodsEntity> promotionGoodsEntityList = vo.getPromotionGoodsList().stream().map(item -> {
                PromotionGoodsEntity promotionGoodsEntity = new PromotionGoodsEntity();
                BeanUtils.copyProperties(item,promotionGoodsEntity);
                promotionGoodsEntity.setPromotionId(vo.getId());
                promotionGoodsEntity.setThumbnail(item.getSkuDefaultImg());
                return promotionGoodsEntity;
            }).collect(Collectors.toList());
            for (PromotionGoodsEntity promotionGoods : promotionGoodsEntityList) {
                promotionGoodsService.saveOrUpdate(promotionGoods);
            }
        }
        if (b){
            return RespBean.success("修改成功");
        }else {
            return RespBean.error("修改失败");
        }
    }

    /**
     * 关闭当前的满减活动
     * @param id
     * @return
     */
    @Override
    public RespBean closeFullDiscount(Long id) {
        boolean update = this.update(new UpdateWrapper<FullDiscountEntity>()
                .set("start_time", null)
                .set("end_time", null)
                .eq("id", id));

        if (update){
            return RespBean.success("关闭活动成功");
        }else {
            return RespBean.error("关闭活动失败");
        }
    }

    /**
     * 重新开启活动
     * @param params
     * @return
     */
    @Override
    public RespBean openFullDiscount(Map<String, Object> params) {
        Long id = Long.parseLong(params.get("id").toString());
        Date startTime = new Date(Long.parseLong(params.get("startTime").toString()));
        Date endTime = new Date(Long.parseLong(params.get("endTime").toString()));

        boolean update = this.update(new UpdateWrapper<FullDiscountEntity>()
                .set("start_time", startTime)
                .set("end_time", endTime)
                .eq("id", id));

        if (update){
            return RespBean.success("开启活动成功");
        }else {
            return RespBean.error("开启活动失败");
        }
    }

    /**
     * 删除满减活动
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RespBean deleteFullDiscount(Long id) {
        FullDiscountEntity fullDiscountEntity = this.getById(id);

        if (fullDiscountEntity.getScopeType().equals("PORTION_GOODS")){
            // 如果有关联的或者指定范围的商品要一起删掉活动数据
            List<PromotionGoodsEntity> promotionGoodsList = promotionGoodsService
                    .list(new QueryWrapper<PromotionGoodsEntity>().eq("promotion_id", id));
            List<Long> ids = promotionGoodsList.stream().map(PromotionGoodsEntity::getId).collect(Collectors.toList());
            // 删除和它关联的活动商品
            promotionGoodsService.removeByIds(ids);
        }

        // 删除满减活动本体
        boolean b = this.removeById(id);
        if (b){
            return RespBean.success("删除成功");
        }else{
            return RespBean.error("删除成功");
        }
    }

    /**
     * 获取商城管理端的满减活动分页数据
     * @param vo
     * @param param
     * @return
     */
    @Override
    public RespBean getManagerFullDiscountPage(PageVO vo, ManagerFullDiscountSearchParam param) {
        IPage<ManagerFullDiscountPageVo> page = this.baseMapper.getManagerFullDiscountPage(PageUtil.initPage(vo),param,new Date());

        FullDiscountEntity entity = new FullDiscountEntity();
        for (ManagerFullDiscountPageVo record : page.getRecords()) {
            BeanUtils.copyProperties(record,entity);
            record.setPromotionStatus(entity.getPromotionStatus());
        }

        return RespBean.success("获取成功",page);
    }

    /**
     * 获取商城官方后台的满减活动的详情
     * @param id
     * @return
     */
    @Override
    public RespBean getManagerFullDiscountDetail(Long id) {
        AddFullDiscountVo vo = new AddFullDiscountVo();
        FullDiscountEntity fullDiscount = this.getById(id);
        BeanUtils.copyProperties(fullDiscount,vo);

        if (fullDiscount.getScopeType().equals("PORTION_GOODS")){
            // 如果指定了商品范围
            List<PromotionGoodsEntity> promotionGoodsEntityList = promotionGoodsService
                    .list(new QueryWrapper<PromotionGoodsEntity>()
                            .eq("promotion_id", id));
            List<PromotionGoodsVo> result = promotionGoodsEntityList.stream().map(item -> {
                PromotionGoodsVo promotionGoodsVo = new PromotionGoodsVo();
                BeanUtils.copyProperties(item,promotionGoodsVo);
                promotionGoodsVo.setSkuDefaultImg(item.getThumbnail());
                return promotionGoodsVo;
            }).collect(Collectors.toList());
            vo.setPromotionGoodsList(result);
        }

        return RespBean.success("获取成功",vo);

    }

    /**
     * 获取商品详情里的满减优惠的信息
     * @param skuId
     * @return
     */
    @Override
    public RespBean getProductDetailFullDiscount(Long skuId) {
        List<FullDiscountEntity> result = new ArrayList<>();
        // 先查询出当前正在进行中的满减活动
        List<FullDiscountEntity> STARTFullDiscount = this.list(new QueryWrapper<FullDiscountEntity>()
                .lt("start_time", new Date())
                .gt("end_time", new Date()));

        // 过滤出使用范围是全品类的满减优惠
        List<FullDiscountEntity> ALLFullDiscount = STARTFullDiscount.stream().filter(item -> {
            return item.getScopeType().equals("ALL");
        }).collect(Collectors.toList());
        for (FullDiscountEntity entity : ALLFullDiscount) {
            result.add(entity);
        }

        // 在进行中的过滤出当前指定当前sku可用的满减活动
        List<PromotionGoodsEntity> promotionGoodsEntityList = promotionGoodsService
                .list(new QueryWrapper<PromotionGoodsEntity>()
                        .eq("sku_id", skuId));
        List<Long> promotionIds = promotionGoodsEntityList.stream().map(PromotionGoodsEntity::getPromotionId).collect(Collectors.toList());
        List<FullDiscountEntity> PORTION_GOODS_FullDiscount = STARTFullDiscount.stream().filter(item -> {
            return item.getScopeType().equals("PORTION_GOODS");
        }).collect(Collectors.toList());
        for (FullDiscountEntity entity : PORTION_GOODS_FullDiscount) {
            for (Long promotionId : promotionIds) {
                if (entity.getId().equals(promotionId)){
                    result.add(entity);
                }
            }
        }

        return RespBean.success("获取成功",result);
    }

    /**
     * 获取购物车结算时可用的满减活动
     * @param skuIds
     * @return
     */
    @Override
    public List<FullDiscountEntity> getCartCheckFullDiscount(List<Long> skuIds) {
        List<FullDiscountEntity> result = new ArrayList<>();
        // 先查询出当前正在进行中的满减活动
        List<FullDiscountEntity> STARTFullDiscount = this.list(new QueryWrapper<FullDiscountEntity>()
                .lt("start_time", new Date())
                .gt("end_time", new Date()));
        // 过滤出使用范围是全品类的满减优惠
        List<FullDiscountEntity> ALLFullDiscount = STARTFullDiscount.stream().filter(item -> {
            return item.getScopeType().equals("ALL");
        }).collect(Collectors.toList());
        for (FullDiscountEntity entity : ALLFullDiscount) {
            result.add(entity);
        }

        // 过滤出当前SkuIds集合中可用的满减优惠券
        List<PromotionGoodsEntity> promotionGoodsEntityList = promotionGoodsService
                .list(new QueryWrapper<PromotionGoodsEntity>()
                .in("sku_id", skuIds));
        List<Long> promotionIds = promotionGoodsEntityList.stream().map(PromotionGoodsEntity::getPromotionId).collect(Collectors.toList());
        List<FullDiscountEntity> PORTION_GOODS_FullDiscount = STARTFullDiscount.stream().filter(f -> {
            return f.getScopeType().equals("PORTION_GOODS");
        }).collect(Collectors.toList());
        for (FullDiscountEntity entity : PORTION_GOODS_FullDiscount) {
            for (Long promotionId : promotionIds) {
                if (entity.getId().equals(promotionId)){
                    result.add(entity);
                }
            }
        }

        return result;
    }


































}
